window.log = null;
window.osh = null;

function window::onload()
{
	window.log = new Log();

	window.osh = OSH.getCurrent();

	var pluginsFrame = window.top.frames["pluginsFrame"];
	if(pluginsFrame != null && pluginsFrame.location != null)
		pluginsFrame.location.replace("/Plugins/Index.html");

	var transparentColor = window.top.document.body.currentStyle.backgroundColor;
	var transparentColorValue = parseInt(transparentColor.replace("#", "0x"));
	if(!isNaN(transparentColorValue))
		OSH.getHost().Osh.TransparentColor = transparentColorValue;
	else
		window.top.log.writeln("Incorrect transparent color: '" + transparentColorValue + "'.");
	
	window.osh.resizeTo(720, 576);
	window.osh.navigator.go("Home");
	window.osh.hide();
}

function window::onunload()
{
	if(window.top.OSH)
		window.top.OSH.getHost().DetachAllEvents();
}

window._keyHandled = false;
window.onKeyDown = function(event)
{
	if(event.keyCode < 0x20 && event.keyCode != 13)
	{
		log.writeln("keydown: " + event.keyCode);
		window._keyHandled = true;
		osh.processKey(event.keyCode, null, null);
	}
	else
	{
		log.writeln("keydown: " + event.keyCode + " (processing delayed)");
		window._keyHandled = false;
	}
}

window.onKeyPress = function(event)
{
	log.writeln("keypress: " + event.keyCode);
	window._keyHandled = true;
	osh.processKey(event.keyCode, null, null);
}

window.onKeyUp = function(event)
{
	if(!window._keyHandled)
	{
		log.writeln("keyup: " + event.keyCode);
		window._keyHandled = true;
		osh.processKey(event.keyCode, null, null);
	}
	else
		log.writeln("keyup: " + event.keyCode + " (already handled)");
}

document.onkeydown = function() { window.top.onKeyDown(event); }
document.onkeypress = function() { window.top.onKeyPress(event); }
document.onkeyup = function() { window.top.onKeyUp(event); }

function getFirstLines(text, numberOfLines)
{
	var re = new RegExp("^\\s*function\\s*\\(", "im");
	if(!re.test(text))
		numberOfLines = 1
	
	var	textLines = text.split("\r\n");
	var result = textLines.slice(0, numberOfLines);
	result = result.join("\r");
	if(numberOfLines > 1 && numberOfLines < textLines.length)
		result += "\r...";
	return result;
}

function onError(sMsg, sUrl, sLine)
{
	try
	{
		return onErrorEx(sMsg, sUrl, sLine);
	}catch(e){}
}

function onErrorEx(sMsg, sUrl, sLine)
{
	var callStack = "";
	if(onError.caller)
	{
		callStack = "-----\r" + getFirstLines(onError.caller.toString(), 10) + "\r-----\r";
		var caller = onError.caller.caller;
		for(var i = 0; i < 10 && caller; i++)
		{
			callStack += getFirstLines(caller.toString(), 10) + "\r-----\r";
			caller = caller.caller;
		}
	}
	
	var errorMessage = "";
	try
	{
		errorMessage = 
			"URL: " + sUrl + "\r" +
			"Line: " + sLine + "\r" +
			"Error: " + sMsg;
		log.error(errorMessage);
	}
	catch(e){}

	var config = Configuration.getHostConfig();
	if(config && !config.ShowScriptErrors)
		return true;

	if(confirm(errorMessage + "\r\r Press Cancel to view detailed information about this error."))
		return true;
	
	var errorMessage = 
		"URL: " + sUrl + "\r" +
		"Line: " + sLine + "\r" +
		"Error: " + sMsg + "\r" +
		"Call Stack: " + "\r" + 
		callStack + "\r\r" +
		"Press Ctrl+C if you want to copy this message.";
	alert(errorMessage);
	return true;
}
window.onerror = onError;

writeDefaultHeader = function(win)
{
	writeDefaultScripts(win);
	writeDefaultStyles(win);
}

writeDefaultScripts = function(win)
{
	win.osh = window.top.osh;
	win.document.writeln("<" + "script language='javascript'>" +
		"window.top.Type.exportTypes(window); " + 
		"var screen = window.top.Screen.getScreenByHref(location.href); " +
		"window.onerror = window.top.onError; " + 
		"document.onkeydown = function() { window.top.onKeyDown(event); }; " +
		"document.onkeypress = function() { window.top.onKeyPress(event); }; " +
		"document.onkeyup = function() { window.top.onKeyUp(event); }; " +
		"</" + "script>");

}

writeDefaultStyles = function(win)
{
	win.document.writeln("<link rel='stylesheet' type='text/css' href='/Themes/" + 
		window.top.osh.getThemeName() + "/Styles.css' />");
}

importCommonOshControl = function(win, controlName)
{
	win.document.writeln("<?import namespace='osh' implementation='/Themes/Common/Controls/" + controlName + "'?>");
}

importThemedOshControl = function(win, controlName)
{
	win.document.writeln("<?import namespace='osh' implementation='/Themes/" + 
		window.top.osh.getThemeName() + "/Controls/" + controlName + "'?>");
}


//**********************************************************
// Log
//**********************************************************
function Log()
{
	var _traceSource = OSH.getHost().ScriptTraceSource;
	var _newLineStr = "\r";
	// Summary:
	//     Identifies the type of event that has caused the trace.
	
	this.writeln = function(entry)
	{
		_traceSource.Write(entry);
	}

	this.error = function(message)
	{
		_traceSource.Error(message);
	}

	this.exception = function(exception, message)
	{
		message = (message == null ? "" : message + " ");
		_traceSource.Error(message + "Exception: " + exception.number + " (" + exception.description + ")");
	}

	// Move to Debug
	this.dump = function(obj)
	{
		var result = "";
		if(obj == null)
			result = "null";
		else if(typeof(obj) == "object" || typeof(obj) == "array")
		{
			result = typeof(obj) + _newLineStr;
			for(var prop in obj)
				result += prop + ": " + typeof(obj[prop]) + ": " + obj[prop] + _newLineStr;
		}
		else
			result = obj.toString();
		return result;
	}

	this.dumpStr = function(str)
	{
		var result = "";
		if(str != null)
		{
			for(var i = 0; i < str.length; i++)
			{
				if(i > 0) result += " ";
				result += str.charCodeAt(i).toString(16);
			}
		}
		else
			str = "null";
		return result;
	}

}
Type.registerType('Log');



//**********************************************************
// Configuration
//**********************************************************
function Configuration()
{
}

Configuration.getCurrent = function()
{
	return OSH.getHost().OshConfiguration;
}

Configuration.getHostConfig = function()
{
	return OSH.getHost().HostConfiguration;
}

Configuration.readKeysConfig = function(keysCollection)
{
	var keysArray = new Enumerator(keysCollection).toArray()
	var keys = null;
	if(keysArray)
	{
		keys = [];
		for(var i = 0; i < keysArray.length; i++)
		{
			var key = {};
			key.name = keysArray[i].Name;
			key.code = Keys.parseKey(key.name);
			key.command = keysArray[i].Command;
			if(key.name && key.code)
				keys[key.code] = key;
		}
	}	
	return keys;
}
Type.registerType('Configuration');
